package handler

import (
	"fmt"
	"io"
	"net/http"
	"yunpan/pool"
	"yunpan/store/ceph"

	"github.com/gin-gonic/gin"
)

// StreamUploadHandler 处理流上传
func StreamUploadHandler(c *gin.Context, cephPool *pool.CephWorkerPool) {
	// 1. 验证请求
	username := c.MustGet("username").(string)
	if username == "" {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg" : "未授权",
		})
		return
	}

	// 2. 获取流信息
	streamName := c.Query("stream")
	if streamName == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg" : "缺少流名称",
		})
		return
	}

	// 3. 创建 RTMP 读取器
	reader := c.Request.Body

	// 4. 提交存储任务
	cephTask := pool.NewCephTask(
		username,
		"上传流",
		3,
		func(conn *ceph.StorageSession) error {
			streamPath := fmt.Sprintf("streams/%s.flv", streamName)
			return conn.UploadStream(streamPath, reader)
		},
	)

	if err := cephPool.Submit(cephTask); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg" : "提交存储任务失败",
		})
		return
	}

	// 5. 等待任务完成
	if err := cephTask.Wait(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg" : "上传失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg" : "Stream upload succeeded",
	})
}

// StreamPlayHandler 处理流播放
func StreamPlayHandler(c *gin.Context) {
	username := c.MustGet("username").(string)
	streamName := c.Query("stream")

	cephConn, err := ceph.GetCephConn(username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg" : "获取存储连接失败",
		})
		return
	}

	streamPath := fmt.Sprintf("streams/%s.flv", streamName)

	// 设置响应头，支持流式传输
	c.Header("Content-Type", "video/x-flv")
	c.Header("Transfer-Encoding", "chunked")

	// 从 Ceph 读取流并发送
	reader, err := cephConn.GetObjectReader(streamPath)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg" : "获取流失败",
		})
		return
	}
	defer reader.Close()

	// 使用 io.Copy 进行流式传输
	io.Copy(c.Writer, reader)
}
